package com.e3.web.core.model;

import com.extjs.gxt.ui.client.data.ModelComparer;
import com.extjs.gxt.ui.client.data.ModelKeyProvider;

public class ModelHelper<T extends SuperModel> {

	/**
	 * tree和grid利用该比较器实现moudle的find和update。
	 * 
	 * @return
	 */
	public boolean compare(T m1, T m2) {
		if (m1 == m2) {
			return true;
		}
		if ((m1 == null && m2 != null) || (m2 == null && m1 != null)) {
			return false;
		}
		if (m1 != null) {
			return m1.getModelId().equals((m2 == null ? "" : m2.getModelId()));
		}
		if (m2 != null) {
			return m2.getModelId().equals((m1 == null ? "" : m1.getModelId()));
		}
		return false;
	}

	public ModelKeyProvider<T> getModelKeyProvider() {
		return new ModelKeyProvider<T>() {

			public String getKey(T model) {
				return model.getModelId()+"";
			}

		};
	}

	public ModelComparer<T> getModelComparer() {
		return new ModelComparer<T>() {

			public boolean equals(T m1, T m2) {
				if (m1 == m2) {
					return true;
				}
				if ((m1 == null && m2 != null) || (m2 == null && m1 != null)) {
					return false;
				}
				if (m1 != null) {
					return m1.getModelId().equals((m2 == null ? "" : m2.getModelId()));
				}
				if (m2 != null) {
					return m2.getModelId().equals((m1 == null ? "" : m1.getModelId()));
				}
				return false;
			}
			
		};
	}

}
